<template>
  <div>
    <div class="upload-img-box">
      <div class="upload-no-img" v-if="!img" >
        <img class="upload-img-icon" src="https://djb.oss-cn-shanghai.aliyuncs.com/7c047c689ff50fa07924306b4248993.png">
        <div class="upload-no-img-text">将文件拖到此处，或点击上传</div>
        <div class="upload-no-img-text">智能上传jpg/png文件</div>
      </div>
      <img :src="img" class="upload-img-url" v-else/>
      <input type="file" class="upload-img-file" @change="upload($event)" ref="multifile"/>
      <!--            <i-circle :percent="progress" class="upload-process" :size="size ? size : 80" v-if="load"></i-circle>-->
    </div>
  </div>
</template>

<script>
export default {
  props: {img_url: {}, file_name: {}, size: {}, old: {}},
  data() {
    return {
      img: "",
      load: false,
      progress: 0
    };
  },
  mounted() {
    this.img = this.img_url;
  },
  methods: {
    //选择文件
    upload(e) {
      var file = e.currentTarget.files;
      this.fileUpload(file[0]);
    },
    //上传文件
    fileUpload(img) {
      if (img == undefined) return false;
      //获取文件后缀名
      var arr = img["name"].split(".");
      var img_type = arr[1];
      let OSS = require("ali-oss");
      let client = new OSS({
        region: this.$region,
        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
        accessKeyId: this.$accessKeyId,
        accessKeySecret: this.$accessKeySecret,
        bucket: this.$bucket
      });
      // client.options.endpoint.protocol = "https:";
      //获取当前时间
      var date = new Date();
      var file_name =
          date.getFullYear() +
          "/" +
          (date.getMonth() + 1) +
          "/" +
          date.getDate() +
          "/" +
          date.getHours() +
          "_" +
          date.getMinutes() +
          "_" +
          date.getSeconds() +
          "_" +
          date.getMilliseconds();
      let filename = this.file_name + file_name + "." + img_type;
      let res_file = img;
      let that = this;

      async function put() {
        var fielinput = that.$refs['multifile'];
        fielinput.value = '';
        try {
          //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
          await client
              .multipartUpload(filename, res_file, {
                progress: percentage => {
                  that.progress = parseInt(percentage * 100);
                  console.log('上传进度：' + that.progress);
                  //console.log(percentage); // 上传文件进度
                }
              })
              .then(res => {
                // that.img = that.old ? res.name :that.$oss_url + res.name;
                that.$emit("change", that.$oss_url + res.name);
                setTimeout(() => {
                  that.load = false;
                }, 500);
                //that.$emit("change", res.name);
              })
              .catch(err => {
                console.log(err);
                setTimeout(() => {
                  that.load = false;
                }, 500);
                return that.$Message.error("文件上传失败");
                //return that.toast(0, "上传失败");
              });
        } catch (e) {
          setTimeout(() => {
            that.load = false;
          }, 500);
          return that.$Message.error("文件上传失败");
        }

      }

      this.load = true;
      this.progress = 0;
      put();
    }
  },
  watch: {
    img_url: {
      handler(v, o) {
        console.log(v, o);
        this.img = this.img_url;
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.upload-process {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.upload-img-box {
  width: 300px;
  height: 180px;
  border: 1px dashed #D2D5DB;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
  position: relative;
  color: #999;
  overflow: hidden;
}



.upload-no-img{
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
  align-items: center;
  justify-content: center;
}

.upload-img-icon{
  display: block;
  width:60px;
}

.upload-no-img-text{
  color: #999999;
  font-size: 12px;
  line-height: 20px;
}

.upload-img-url {
  width: 100%;
  height: 100%;
}

.upload-img-file {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0;
  cursor: pointer;
}
</style>